package com.xhtt.modules.app.controller.cfg;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.Constant;
import com.xhtt.common.utils.ExportExcel;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.R;
import com.xhtt.modules.app.annotation.Login;
import com.xhtt.modules.app.annotation.LoginUser;
import com.xhtt.modules.cfg.entity.*;
import com.xhtt.modules.cfg.model.ValidPotParam;
import com.xhtt.modules.cfg.service.CfgPotInfoService;
import com.xhtt.modules.cfg.service.CfgPotProductService;
import com.xhtt.modules.cfg.service.CfgPotRelateService;
import com.xhtt.modules.sys.controller.AbstractController;
import com.xhtt.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 罐库 前端控制器
 * </p>
 *
 * @author feipc
 * @since 2019-02-21
 */
@Api(tags = "任务平台-基础数据维护-罐库列表", value = "任务平台-基础数据维护-罐库列表")
@RestController
@RequestMapping("app/sys/cfg/pot")
public class CfgPotInfoController extends AbstractController {

    @Autowired
    private CfgPotInfoService cfgPotInfoService;
    @Autowired
    private CfgPotProductService cfgPotProductService;
    @Autowired
    private CfgPotRelateService potRelateService;


    /**
     * 获取罐库列表
     */
    @GetMapping(value = "/list")
    @ApiOperation("获取罐库列表(web/app)")
    @Login
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = cfgPotInfoService.queryPage(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 新增罐库
     */
    @PostMapping(value = "/add")
    @ApiOperation("新增罐库(web)")
    @Login
    public R add(@RequestBody CfgPotInfo cfgPotInfo) {
        cfgPotInfoService.addPot(cfgPotInfo);
        return R.ok();
    }

    /**
     * 删除罐库
     */
    @PostMapping(value = "/delete")
    @ApiOperation("删除罐库(web)")
    @Login
    public R delete(@RequestBody Integer[] ids) {
        //假删除
        CfgPotInfo p = new CfgPotInfo();
        p.setStatus(-1);
        cfgPotInfoService.update(p, new UpdateWrapper<CfgPotInfo>().in(CfgPotInfo.ID, Arrays.asList(ids)));
        return R.ok();
    }

    /**
     * 修改罐库
     */
    @PostMapping(value = "/update")
    @ApiOperation("修改罐库(web)")
    @Login
    public R update(@RequestBody CfgPotInfo cfgPotInfo, @ApiIgnore @LoginUser SysUserEntity user) {
        MDC.put("deptUser", user.getDeptName() + "-" + user.getName());
        cfgPotInfoService.updatePot(cfgPotInfo);
        return R.ok();
    }

    /**
     * app修改rfid
     */
    @PostMapping(value = "/updateRfid")
    @ApiOperation("app修改rfid(app)")
    @Login
    public R updateRfid(@RequestBody CfgPotInfo cfgPotInfo, @ApiIgnore @LoginUser SysUserEntity user) {
        MDC.put("deptUser", user.getDeptName() + "-" + user.getName());
        cfgPotInfoService.updateRfid(cfgPotInfo);
        return R.ok();
    }

    /**
     * 获取罐修改日志
     */
    @GetMapping(value = "/logList")
    @ApiOperation("获取罐修改日志(web)")
    @Login
    public R logList(@RequestParam Map<String, Object> params) {
        PageUtils page = cfgPotInfoService.logList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 获取罐库
     */
    @GetMapping(value = "/get/{id}")
    @ApiOperation("获取罐库(web/app)")
    @Login
    public R get(@PathVariable("id") Integer id) {
        CfgPotInfo pot = cfgPotInfoService.getById(id);
        CfgPotProduct PotProduct = cfgPotProductService.getOne(new LambdaQueryWrapper<CfgPotProduct>().eq(CfgPotProduct::getPotId, pot.getId()));
        pot.setPotProduct(PotProduct);
        return R.ok().put(Constant.DATA, pot);
    }

    /**
     * 查看罐连接点
     */
    @GetMapping(value = "/getRelateObject")
    @ApiOperation("查看罐连接点(web/app)")
    @Login
    public R getRelateObject(@RequestParam Integer potId) {
        List<CfgPotRelate> relates = cfgPotInfoService.getRelateObject(potId);
        return R.ok().put(Constant.DATA, relates);
    }

    /**
     * 查看罐可用的连接点
     */
    @GetMapping(value = "/getValidRelateObject")
    @ApiOperation("查看罐可用的连接点(web)")
    @Login
    public R getValidRelateObject(ValidPotParam param) {
        List<CfgPotRelate> relates = potRelateService.getValidRelateObject(param);

        List<Integer> selectedPumpIds = param.getSelectedPumpIds();
        List<Integer> selectedTubeIds = param.getSelectedTubeIds();
        if (CollectionUtils.isNotEmpty(selectedPumpIds)) {
            Iterator<CfgPotRelate> it = relates.iterator();
            while (it.hasNext()) {
                CfgPotRelate r = it.next();
                if (3 == r.getType().intValue() && selectedPumpIds.contains(r.getRelateId())) {
                    it.remove();
                }
            }
        }
        if (CollectionUtils.isNotEmpty(selectedTubeIds)) {
            Iterator<CfgPotRelate> it = relates.iterator();
            while (it.hasNext()) {
                CfgPotRelate r = it.next();
                if (2 == r.getType().intValue() && selectedTubeIds.contains(r.getRelateId())) {
                    it.remove();
                }
            }
        }
        return R.ok().put(Constant.DATA, relates);
    }

    /**
     * 修改罐连接点
     */
    @PostMapping(value = "/updateRelateObject")
    @ApiOperation("修改罐连接点(web)")
    @Login
    public R updateRelateObject(@RequestBody List<CfgPotRelate> relates) {
        cfgPotInfoService.updateRelateObject(relates);
        return R.ok();
    }

    @GetMapping(value = "/export")
    @ApiOperation("储罐列表导出")
    @Login
    public void export(HttpServletResponse response, @RequestParam Map<String, Object> params) {
        ExportExcel exportExcel = new ExportExcel();
        params.put("limit", "650000");
        PageUtils page = cfgPotInfoService.queryPage(params);
        List list = page.getList();
        String fileName = "储罐数据";
        String sheetName = "sheet1";
        String[] headers = {"储罐编号", "位置", "目前产品", "材质", "保温", "是否有尾气系统"};
        String[] columns = {"numberNo", "workAreaName", "comUsedProd", "texture", "insulation", "ifOffGasSysStr"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }

    @GetMapping(value = "/logExport")
    @ApiOperation("储罐操作记录导出")
    @Login
    public void logExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {
        ExportExcel exportExcel = new ExportExcel();
        Object potId = params.get("id");
        CfgPotInfo pot = cfgPotInfoService.getOne(new LambdaQueryWrapper<CfgPotInfo>().eq(CfgPotInfo::getId, potId).select(CfgPotInfo::getId, CfgPotInfo::getNumberNo));
        PageUtils page = cfgPotInfoService.logList(params);
        List list = page.getList();
        String fileName = "储罐(" + pot.getNumberNo() + ")操作记录";
        String sheetName = "储罐操作记录";
        String[] headers = {"记录时间", "操作人", "目前产品", "位置", "RFID"};
        String[] columns = {"createTime", "deptUser", "productInfo", "workAreaInfo", "rfidInfo"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }
}
